<template>
  <basic-layout>
    <view class="user-center">
      <!-- 顶部用户信息 -->
      <view class="user-header">
        <view class="user-info">
          <image class="avatar" :src="avatarUrl" mode="aspectFill" />
          <view class="v-info">
            <template v-if="user.nickName">
              <view class="login-text" v-if="user.nickName">
                {{ user.nickName }}
              </view>
            </template>
            <text class="login-text" v-else @tap="handleLogin"> 去登录 </text>
            <view class="my-w">我的资料</view>
          </view>
        </view>
        <!-- <image
          class="qr-icon"
          :src="qrcodeIcon"
          mode="aspectFit"
          @tap="clickCode"
        /> -->
      </view>

      <myTab />

      <!-- <template v-if="!isBusiness">
        <businessCut />
        <businessTab />
      </template>
      <template v-else>
        <myCut />
        <myTab />
      </template> -->

      <!-- 设置功能区 -->
      <view class="function-section">
        <!-- <view class="section-title">其他服务</view> -->
        <view class="service-list">
          <view
            class="service-item"
            v-for="item in serviceItems"
            :key="item.text"
            @tap="goToService(item)"
          >
            <image class="icon" :src="item.icon" mode="aspectFit" />
            <text class="title">{{ item.text }}</text>
            <image class="arrow" :src="arrowIcon" mode="aspectFit" />
          </view>
        </view>
      </view>
    </view>
  </basic-layout>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed } from "vue";
import myCut from "./my-cut.vue";
import businessCut from "./business-cut.vue";
import myTab from "./my-tab.vue";
import businessTab from "./business-tab.vue";
import Taro from "@tarojs/taro";

import BasicLayout from "@/layouts/basic-layout.vue";

import qrcodeIcon from "@/assets/imgs/code.svg";
import arrowIcon from "@/assets/imgs/right.svg";

// 服务图标
import deleteIcon from "@/assets/imgs/setting.svg";
import feedbackIcon from "@/assets/imgs/yijian.svg";
import questionIcon from "@/assets/imgs/wenti.svg";
import infoIcon from "@/assets/imgs/we.svg";
import protectIcon from "@/assets/imgs/xiyi.svg";
import groupIcon from "@/assets/imgs/team.svg";
import locationIcon from "@/assets/imgs/addr.svg";
import serviceIcon from "@/assets/imgs/server.svg";

import shareIcon from "@/assets/imgs/share.png";
import quanIcon from "@/assets/imgs/quan.png";

import http from "@/utils/http";
import { buildUrlParams } from "@/utils/tooler";
import { globalState } from "@/store/globalStore";

import { store } from "@/store/index";
const { info, user, userType } = store.storeState;

const avatar = ref("https://cdn.tjkximg.com/content/zhangtang/images/mtjx.jpg");
// import { useCounterStore } from "@/store/counter";
const isBusiness = computed(() => {
  return userType.value == "B";
});

const avatarUrl = computed(() => {
  if (user.value.avatarUrl) {
    return user.value.avatarUrl;
  }
  return avatar.value;
});

// setTimeout(() => {
//   store.num.value = 20
// }, 2000);

// const counterStore = useCounterStore();

// const isBusiness = ref(false);

const userInfo = ref<any>({});

Taro.setNavigationBarTitle({
  title: "我的",
});

onMounted(() => {});

const serviceItems = ref([
  { icon: groupIcon, text: "我的资料" },
  // { icon: quanIcon, text: "优惠券" },
  { icon: serviceIcon, text: "联系客服" },
  { icon: protectIcon, text: "用户隐私" },
  { icon: shareIcon, text: "分享好友" },
]);

const goToService = (item) => {
  if (item.text === "收货地址") {
    Taro.navigateTo({
      url: "/pages-detail/my/address",
    });
    return;
  }
  if (item.text === "联系客服") {
    Taro.openCustomerServiceChat({
      extInfo: {url: 'https://work.weixin.qq.com/kfid/kfc26fae0a5103e0d76'},
      corpId: 'ww2daa22580a8f83c5',
    })
    return;
  }
  // else if(item.text === "联系客服") {
  //   Taro.navigateTo({
  //     url: "/pages-detail/my/order",
  //   });
  // }
};

const clickCode = () => {
  // !.value = !!.value;
  Taro.navigateTo({
    url: "/pages-detail/my/code",
  });
};

const checkLoginStatus = () => {
  Taro.getSetting({
    success: (res) => {
      console.log("res getSetting", res);
      if (res.authSetting["scope.userInfo"]) {
        getUserInfo();
      } else {
        Taro.authorize({
          scope: "scope.userInfo",
          success: () => {
            getUserInfo();
          },
          fail: () => {
            Taro.showModal({
              title: "提示",
              content: "您需要授权才能获取头像和昵称",
              success: (res) => {
                if (res.confirm) {
                  Taro.openSetting({
                    success: (settingRes) => {
                      console.log("res settingRes", res);
                      if (settingRes.authSetting["scope.userInfo"]) {
                        getUserInfo();
                      }
                    },
                  });
                }
              },
            });
          },
        });
      }
    },
  });
};

const getUserInfo = async () => {
  return new Promise((resolve, reject) => {
    Taro.getUserProfile({
      desc: "用于完善会员资料",
      force: true,
      success: async (res) => {
        console.log("用户信息", res.userInfo);
        resolve(res.userInfo);
      },
      fail: (err) => {
        console.error("获取用户信息失败", err);
        reject(err);
      },
    });
  });
};

const handleLogin = async () => {
  // checkLoginStatus();
  // return;
  const res = await getUserInfo();
  userInfo.value = res;
  console.log("userInfo", userInfo.value);
  store.setUser(userInfo.value);
  // return
  const loginRes = await Taro.login();
  console.log("loginRes", loginRes);
  // return;

  if (loginRes.code) {
    console.log("code:", res);
    http
      .post(
        buildUrlParams("/api/weixin/getToken", {
          code: loginRes.code,
          nickName: res.nickName,
          avatarUrl: res.avatarUrl,
          referralCode: "",
        }),
        null,
        { headers: { token: "1" } }
      )
      .then((res) => {
        console.log("res", res);
        // return;
        if (res.code === 0) {
          // isBusiness.value = res.data.userType == "B";
          globalState.setToken(res.data.token);
          // globalState.getUserInfo();
          store.setToken(res.data.token);
          store.setUserType(res.data.userType);
          store.getUserInfo();
        }
      });
  }
};

const goToRecharge = () => {
  Taro.navigateTo({
    url: "/pages-detail/my/recharge",
  });
};
</script>

<style lang="scss">
.basic-layout__content {
  width: 750rpx;
  background: #f0f0f0;
}
.user-center {
  min-height: 100vh;
  padding-bottom: 100rpx;

  &::after { 
    content: "";
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 300rpx;
    background-color: #000;
    display: block;
  }

  .user-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 60rpx 40rpx 40rpx;
    position: relative;
    z-index: 1;

    .user-info {
      display: flex;
      align-items: center;

      .avatar {
        width: 120rpx;
        height: 120rpx;
        border-radius: 50%;
        margin-right: 30rpx;
        background-color: #eee;
      }

      .login-text {
        font-size: 36rpx;
        font-weight: 600;
        color: #fff;
      }
    }

    .qr-icon {
      width: 40rpx;
      height: 40rpx;
    }
  }

  .function-section {
    background: #fff;
    margin: 30rpx;
    border-radius: 20rpx;
    padding: 0 20rpx;
    box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.04);

    .section-title {
      padding: 30rpx 0;
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      border-bottom: 1rpx solid #f5f5f5;
    }

    // 订单网格
    .order-grid {
      display: flex;
      padding: 30rpx 0;

      .order-item {
        flex: 1;
        display: flex;
        flex-direction: column;
        align-items: center;

        .icon {
          width: 48rpx;
          height: 48rpx;
        }

        text {
          margin-top: 16rpx;
          font-size: 26rpx;
          color: #666;
        }
      }
    }

    // 服务列表
    .service-list {
      .service-item {
        display: flex;
        align-items: center;
        padding: 30rpx 0;
        position: relative;

        &::after {
          content: "";
          position: absolute;
          left: 0;
          right: 0;
          bottom: 0;
          height: 1rpx;
          background-color: #f5f5f5;
        }

        .icon {
          width: 36rpx;
          height: 36rpx;
          margin-right: 20rpx;
        }

        .title {
          flex: 1;
          font-size: 28rpx;
          color: #333;
        }

        .arrow {
          width: 24rpx;
          height: 24rpx;
        }
      }
    }
  }
}

.v-info {
  display: flex;
  flex-direction: column;
  gap: 12rpx;
  .my-w{
    padding: 6rpx 20rpx;
    border: 1rpx solid #fff;
    border-radius: 24rpx;
    color: #333;
    background: #fff;
    font-size: 24rpx;
  }
  .buy-btn {
    width: 120rpx;
    height: 54rpx;
    border-radius: 27rpx;
    // background: hsl(17, 98%, 51%);
    background-color: var(--nut-primary-color);
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 24rpx;
  }
}
</style>
